package com.lanhao.aot.sse;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.lanhao.aot.llm.dto.AIChatDTO;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.model.images.generation.GenerateImagesRequest;
import com.volcengine.ark.runtime.model.images.generation.ImagesResponse;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/sse")
public class SseController {
	private final static Logger LOG = LoggerFactory.getLogger(SseController.class);

    private final ScheduledExecutorService heartbeatScheduler =
            Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

    private final ExecutorService apiExecutor = new ThreadPoolExecutor(
            10, 50,
            60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadPoolExecutor.CallerRunsPolicy() // 队列满时由调用线程执行
    );

	@PostMapping(value = "/ask", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter ask() {
        SseEmitter emitter = new SseEmitter(20_000L); // 超时时间 8 秒

        LOG.info("启动定时状态机发送任务，每隔2秒发送一次...");
        ScheduledFuture<?> heartbeatFuture = heartbeatScheduler.scheduleAtFixedRate(
                () -> {
                    try {
                        emitter.send(SseEmitter.event().comment("心跳状态机")
                                .data("状态机卡片8090" + System.currentTimeMillis()));
                    } catch (IOException e) {

                    }
                },
                0, 2, TimeUnit.SECONDS
        );

        // 模拟调用耗时长的操作
        apiExecutor.execute(() -> {
            try {
                String s = callExternalApi();
                emitter.send(SseEmitter.event().data(s));
            } catch (InterruptedException | IOException e) {
                emitter.completeWithError(e);
            } finally {
                LOG.info("API调用完成了，终止定时发送器");
                heartbeatFuture.cancel(true);
                emitter.complete();
            }
        });

        return emitter;
    }

    private String callExternalApi() throws InterruptedException {
        // 模拟耗时操作（实际替换为真实API调用）
        Thread.sleep(15000); // 15秒延迟
        return "执行耗时API结束，External API result at " + System.currentTimeMillis();
    }
}
